<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;

class Msg extends Model
{
	use \base\model\ModelTrait;
	
    /**
    * 自动添加uniques
    * @return type
    */
    protected $auto= ['uniques'];  
	public function setUniquesAttr($val,$data){
		$uniques = [(String)$data['recive_id'],(String)$data['send_id']]; sort($uniques); 
		return $val ?: md5(join(",",$uniques));
    }
    
    //修改器-内容
	public function setContentAttr($value){
		return htmlspecialchars($value);
    }
    
	//获取器-内容
	public function getContentAttr($value){
		return htmlspecialchars_decode($value);
    }
	
	
	/**
    * 发送消息 
    * @param $send_id 		'发送者id',
    * @param $recive_id 	'接收者id',
    * @param $buess_type '业务类型 0业务消息,1商家消息,2订单消息,3聊天消息',
    * @param $relation_id  '关联id',
    * @return type
    */
	public function send($send_id,$recive_id,$title,$content,$buess_type=0,$relation_id='',$staffId='')
    {
		//保存的数据
		$data = [
			"send_id"			=> $send_id,
			"recive_id"		=> $recive_id,
			"title" 				=> $title,
			"content" 			=> $content,
			"buess_type"		=> $buess_type,
			"unread_num"	=> 1,
			"relation_id"		=> $relation_id,
			"staff_id"			=> $staffId,
			"is_csd"				=> 0
		];
		//如果存在聊天就更新
		if( $msg = self::where(compact('send_id','recive_id','buess_type'))->find() ){
			$msg->content = $data['content'];
			$msg->unread_num = bcadd($msg->unread_num,1,0);
			$msg->add_time = date("Y-m-d H:i:s");
			$res = $msg->save();
		}else{
			$res = self::allowField(true)->save($data);
		}
		
		$res = $res && model('MsgContent')->add($data);
		
		//返回
		return $res ? true : fasle;
    }
	
	
	/**
     * 获取消息列表 
     * @return type
     */
	public function getList($uid)
    {
		$model = model('MsgContent');
		$model = $model->alias('a');
		$model = $model->where('a.recive_id',$uid);
		$model = $model->where('a.buess_type','<>',3);
		$model = $model->order('a.add_time','desc');
		$model = $model->field('a.title,a.content,a.status,a.add_time,a.send_id,a.uniques');
		$model = $model->page( input('pageIndex',1) , input('pageSize',20));
		$msg  = $model->select()->toArray();
		//改为已读状态
		if( count($msg) > 0 ){
			self::where('uniques',$msg[0]['uniques'])
				->where('recive_id',$uid)
				->where('buess_type','<>',3)
				->update(['unread_num'=>0]);

			$res = model('MsgContent')->where('uniques',$msg[0]['uniques'])
				->where('recive_id',$uid)
				->where('status',0)
				->update(['status'=>1]);
		}
		//返回
		return $msg;
    }
	
	
	/**
     * 获取未读消息列表 
     * @return type
     */
	public function userUnreadMsgList($uid)
    {
		$model = new self;
		$model = $model->alias('a');
		$model = $model->rightJoin([ 	
			db("systemUser") ->field("user_guid,user_name,csd_sign")
			->union(function($query){
				$query->name('shop');
				$query->field("concat('shop_',id) as user_guid");
				$query->field('name as user_name');
				$query->field("'' as csd_sign");
				//$query->field('img as headimgurl');
			})
			->union(function($query){
				$query->name('user');
				$query->field("id as user_guid");
				$query->field('nickname as user_name');
				$query->field("'' as csd_sign");
				//$query->field('avatarUrl as headimgurl');
			})
			->buildSql() => 'b'
		],'a.send_id = b.user_guid');
		//$model = $model->where('a.unread_num','>',0);
		$model = $model->where('a.buess_type',3);
		$model = $model->where('a.recive_id',$uid);
		$model = $model->order('a.add_time','desc');
		$model = $model->field('a.content,a.unread_num,a.add_time,a.send_id');
		//$model = $model->field('b.user_name as send_name,b.headimgurl as send_avatarUrl');
		return $model->select();
    }
	
	/**
     * 获取聊天消息列表
     * @return type
     */
	public function getUserChatList($sendId,$reciveId,$pageIndex=1,$pageSize=10)
    {
    	$uniques = [(String)$sendId,(String)$reciveId]; sort($uniques); 
		$uniques = md5(join(",",$uniques));
		$model = model('MsgUser');
		$model = $model->alias('a');
		$model = $model->LeftJoin(
			[ 	
				db("systemUser") ->field("user_guid,user_name,csd_sign")->field( 
					db("systemUpload")->alias('c') 
					->where('c.file_buss_type','用户信息')
					->where('c.file_type','头像')
					->where('c.file_guid = user_guid')
					->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
					->limit(0,1)
					->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
					->buildSql() ." headimgurl"
				)
				->union(function($query){
						$query->name('shop');
						$query->field("concat('shop_',id) as user_guid");
						$query->field('name as user_name');
						$query->field("'' as csd_sign");
						$query->field('img as headimgurl');
				})
				->union(function($query){
						$query->name('user');
						$query->field("id as user_guid");
						$query->field('nickname as user_name');
						$query->field("'' as csd_sign");
						$query->field('avatarUrl as headimgurl');
				})
				->buildSql() => 'b'
			],
			'a.send_id = b.user_guid'
		);
		$model = $model->LeftJoin(
			[ 	
				db("systemUser")->field("user_guid,user_name,csd_sign")->field( 
					db("systemUpload")->alias('c') 
					->where('c.file_buss_type','用户信息')
					->where('c.file_type','头像')
					->where('c.file_guid = user_guid')
					->field("concat('".APP_PATH."/"."',c.file_path ) as file_path")
					->limit(0,1)
					->union("SELECT '".APP_PATH."/Public/images/user_img.jpg' as file_path")
					->buildSql() ." headimgurl"
				)
				->union(function($query){
						$query->name('shop');
						$query->field("concat('shop_',id) as user_guid");
						$query->field("name as user_name");
						$query->field("'' as csd_sign");
						$query->field('img as headimgurl');
				})
				->union(function($query){
						$query->name('user');
						$query->field("id as user_guid");
						$query->field('nickname as user_name');
						$query->field("'' as csd_sign");
						$query->field('avatarUrl as headimgurl');
				})
				->buildSql() => 'c'
			],
			'a.recive_id = c.user_guid'
		);
		$model = $model->LeftJoin('system_upload d',"
			right(d.file_path,36) = substring(a.content,-37,36)
		");
		$model = $model->LeftJoin('shop_staff k',"k.id = a.staff_id");
		$model = $model->field('a.content,a.send_id,a.recive_id,a.add_time');
		$model = $model->field('b.user_name as send_name,b.headimgurl as send_avatarUrl');
		$model = $model->field('c.user_name as recive_name,c.headimgurl as recive_avatarUrl');
		$model = $model->field('ifnull(d.duration,0) as duration');
		$model = $model->field('k.name as staff_name');
		
		$model = $model->where('a.uniques',$uniques);
		$model = $model->page($pageIndex,$pageSize);
		$model = $model->order('a.add_time','asc');
		$msg = $model->select();
		
		//改为已读状态
		if( count($msg) > 0 ){
			
			self::where('uniques',$uniques)
				->where('recive_id',$sendId)
				->where('unread_num','>',0)
				->where('buess_type',3)
				->update(['unread_num'=>0]);
				
			model('MsgUser')->where('uniques',$uniques)
				->where('recive_id',$sendId)
				->where('status',0)
				->update(['status'=>1]);
		}
		
		return $msg;
    }
	
	
}
